/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaPesquisaVeiculoDisponivel.java
 *
 * Created on 22/11/2011, 16:18:09
 */
package interfacegrafica;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import modelo.Veiculo;
import org.apache.log4j.Logger;

/**
 *
 * @author Lucas
 */
public class JanelaPesquisaDisponibilidadeCategoria extends javax.swing.JFrame {
    private static Logger logger = Logger.getLogger(JanelaPesquisaDisponibilidadeCategoria.class);
    /** Creates new form JanelaPesquisaVeiculoDisponivel */
    public JanelaPesquisaDisponibilidadeCategoria() {
        initComponents();
        tabelaCategoriaDisponivel.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        campoCategoria = new javax.swing.JLabel();
        campoBuscaCategoria = new javax.swing.JTextField();
        botaoCancelarCategoriaDisponivel = new javax.swing.JButton();
        botaoPesquisarCategoriaDisponivel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaCategoriaDisponivel = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Disponibilidade de Categorias"));

        campoCategoria.setText("Digite a Categoria:");

        botaoCancelarCategoriaDisponivel.setText("Cancelar");
        botaoCancelarCategoriaDisponivel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarCategoriaDisponivelActionPerformed(evt);
            }
        });

        botaoPesquisarCategoriaDisponivel.setText("Pesquisar");
        botaoPesquisarCategoriaDisponivel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisarCategoriaDisponivelActionPerformed(evt);
            }
        });

        tabelaCategoriaDisponivel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Modelo", "Marca", "Cor", "Placa", "Observações", "Opcionais", "Tipo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabelaCategoriaDisponivel);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(campoCategoria)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(campoBuscaCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(botaoCancelarCategoriaDisponivel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 263, Short.MAX_VALUE)
                                .addComponent(botaoPesquisarCategoriaDisponivel))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoCategoria)
                    .addComponent(campoBuscaCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoCancelarCategoriaDisponivel)
                    .addComponent(botaoPesquisarCategoriaDisponivel))
                .addGap(34, 34, 34)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(167, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarCategoriaDisponivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarCategoriaDisponivelActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarCategoriaDisponivelActionPerformed

    private void botaoPesquisarCategoriaDisponivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisarCategoriaDisponivelActionPerformed
        logger.info("O usuário " + InterfaceGrafica.login + " pesquisou uma categoria de veículos.");
        tabelaCategoriaDisponivel.setVisible(true);
        exibeTabela();
    }//GEN-LAST:event_botaoPesquisarCategoriaDisponivelActionPerformed
    private void exibeTabela(){
        TelaLogin.em.getTransaction().begin();
        Query query = TelaLogin.em.createQuery("from Veiculo v where v.categoria = :qualquer");
        query.setParameter("qualquer", campoBuscaCategoria.getText());
        List lista = new ArrayList<Veiculo>();
        lista = query.getResultList();
        
        Veiculo vec1 = new Veiculo(null, null, null);
        Veiculo vec2;
        
        if (lista.size() == 0) {
            JOptionPane.showMessageDialog(this, "Não há veículos cadastrados nessa categoria", "Erro", 0);
            TelaLogin.em.getTransaction().commit();
        } else {
            
            for (int i = 0; i < lista.size(); i++) {
                vec2 = (Veiculo) lista.get(i);
                tabelaCategoriaDisponivel.setValueAt(vec2.getModelo(), i, 0);
                tabelaCategoriaDisponivel.setValueAt(vec2.getMarca(), i, 1);
                tabelaCategoriaDisponivel.setValueAt(vec2.getCor(), i, 2);
                tabelaCategoriaDisponivel.setValueAt(vec2.getPlaca(), i, 3);
                tabelaCategoriaDisponivel.setValueAt(vec2.getObservacoes(), i, 4);
                tabelaCategoriaDisponivel.setValueAt(vec2.getOpicionais(), i, 5);
                tabelaCategoriaDisponivel.setValueAt(vec2.getTipo(), i, 6);
            }
            TelaLogin.em.getTransaction().commit();
        }
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JanelaPesquisaDisponibilidadeCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JanelaPesquisaDisponibilidadeCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JanelaPesquisaDisponibilidadeCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JanelaPesquisaDisponibilidadeCategoria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JanelaPesquisaDisponibilidadeCategoria().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoCancelarCategoriaDisponivel;
    private javax.swing.JButton botaoPesquisarCategoriaDisponivel;
    private javax.swing.JTextField campoBuscaCategoria;
    private javax.swing.JLabel campoCategoria;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelaCategoriaDisponivel;
    // End of variables declaration//GEN-END:variables
}
